package com.baipiao.permission.backend.config.security;

import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import com.baipiao.permission.backend.entity.response.Res;
import com.baipiao.permission.backend.entity.response.ResStatusEnum;

import java.io.IOException;

/**
 * @Description: 登录失败处理逻辑
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException {
        ResStatusEnum resCode = ResStatusEnum.auth_fail;
        if (e instanceof BadCredentialsException) {
            // 密码错误
            resCode = ResStatusEnum.account_error;
        } else if (e instanceof CredentialsExpiredException) {
            // 密码过期
            resCode = ResStatusEnum.password_expired;
        } else if (e instanceof DisabledException) {
            // 账号不可用
            resCode = ResStatusEnum.account_disable;
        } else if (e instanceof LockedException) {
            // 账号锁定
            resCode = ResStatusEnum.account_locked;
        } else if (e instanceof InternalAuthenticationServiceException) {
            // 用户不存在
            resCode = ResStatusEnum.account_error;
        }
        // 返回json数据
        String res = JSONObject.toJSONString(Res.fail(resCode));// 401，认证失败
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(res);
    }
}
